<script setup>
/**
 * & 文件引入区域
 */

import { ref, onMounted, watch } from "vue";
import { useRouter } from "vue-router";
import {
  getShopInfoListByCondition,
  getHotelInfoByCondition,
} from "@/server/api/shopApi";
import { initMap, dis, getLocation, getDistance } from "@/utils/mapHandle";
import { useIndexStore } from "@/stores/indexStore";
import { useUseStore } from "@/stores/user";
import { showToast, showLoadingToast, closeToast } from "vant";
import HotelRegionSelect from "@/components/JiMan/HotelRegionSelect.vue";
import { useI18n } from "vue-i18n";
const { t } = useI18n();

const useStore = useIndexStore();
/**
 * & 变量声明区
 */

const router = useRouter();
let tabBarTitle = ["Local", "Int'l"];
let hotelData = ref();
let ImgScr = useUseStore().ing;
const value = ref(""); //搜索框
const show = ref(false);
const secondShow = ref(false);
const date1 = ref();
const date2 = ref();
const date = ref();
const dateNum = ref(0);
const showBottom = ref(false);
const adultvalue = ref(1);
const childvalue = ref(1);

const showPopup = () => {
  showBottom.value = true;
};
const getComment = (score) => {
  if (score >= 4 && score <= 5) {
    return "不错";
  } else if (score >= 3 && score < 4) {
    return "良好";
  } else if (score > 0 && score < 3) {
    return "一般";
  } else {
    return "暂无评分";
  }
};
const formatDate = (date) => `${date.getMonth() + 1}月${date.getDate()}日`;
const onConfirm = (value) => {
  console.log("values:", value);
  if (show.value) {
    show.value = false;
    date1.value = formatDate(value);
  }
  if (secondShow.value) {
    secondShow.value = false;
    date2.value = formatDate(value);
  }

  // date2.value = `${formatDate(end)}`;
  console.log("date1:", date1.value);
  // console.log("date2:", date2.value);
  // dateNum.value = Math.floor(
  //   (date1.value.getTime() - date2.value.getTime()) / (60 * 60 * 24)
  // );
};

// 回车触发搜索，调用接口
const search = () => {
  console.log("search");
  getHotelInfo();
};

// 成人减
const decrementQuantity1 = () => {
  if (adultvalue.value > 0) {
    adultvalue.value--;
  }
};

// 成人加
const incrementQuantity1 = () => {
  if (adultvalue.value < 5) {
    adultvalue.value++;
  }
};
// 儿童减
const decrementQuantity2 = () => {
  if (childvalue.value > 0) {
    childvalue.value--;
  }
};

// 儿童加
const incrementQuantity2 = () => {
  if (childvalue.value < 5) {
    childvalue.value++;
  }
};

const activeSort = ref(null);

// 排序选项
const sortOptions = [
  { text: "距离优先", value: null }, // 默认未选择状态
  { text: "按评分降序", value: "scoreDesc" },
  { text: "按评分升序", value: "scoreASC" }
];
let condition = {
  limit: 8,
  page: 1,
  categoryId: "fwefw",
  score: "", // 默认按评分排序
  regionId: useUseStore().hoteCountryCode,
  latitude: "",
  longitude: ""
};

// 切换排序逻辑
const onSortChange = (value) => {
  if (value === "scoreDesc") {
    condition.score = true; // 按评分降序
    isRequire.value = true;
    condition.page = 1; // 重置页码
  } else if (value === "scoreASC") {
    isRequire.value = true;
    condition.page = 1; // 重置页码
    condition.score = false; // 按评分升序
  } else {
    condition.score = ""; // 距离优先
    isRequire.value = true;
    condition.page = 1; // 重置页码
  }
  refreshPage();
};

// 刷新页面数据
const refreshPage = () => {
  console.log("刷新页面数据，条件：", condition);
  showToast({ message: "正在刷新数据...", duration: 1000 });
  // 调用接口获取数据逻辑
  getShopInfoListByConditionFun(condition);
};

//清除搜索并复原初始数据
watch(value, () => {
  if (value.value == "") {
    console.log("watch启动");
    getShopInfoListByConditionFun(condition);
  }
});
/**
 * & 函数区
 */
const toHotelDetailFun = (shopId) => {
  router.push({
    path: "/hotelResource",
    query: {
      shopId: shopId,
    },
  });
};

let locationArr = ref([]);
const list = ref([]);
// new酒店列表
const getShopInfoListByConditionFun = async (params) => {
  let res = await getShopInfoListByCondition(params);
  hotelData.value = res.data.data;
  list.value = res.data.data.list;
  console.log("酒店列表数据", hotelData.value);
  console.log("contaniner.value", contaniner.value);

  // 清空之前的距离数据，防止上次的数据影响
  locationArr.value = [];

  // 获取当前位置并计算距离
  await getLocation();

  for (const { localhostLatitude, localhostLongitude } of hotelData.value
    .list) {
    let local = getDistance([localhostLatitude, localhostLongitude]);
    locationArr.value.push(local);
  }
};

const getShopInfoListByConditionRegiond = async (params) => {
  let res = await getShopInfoListByCondition(params);
  hotelData.value = res.data.data;
  list.value = res.data.data.list;
  console.log("酒店列表数据", hotelData.value);
  // 显示酒店数量
  if (hotelData.value.count > 0) {
    console.log("数量", hotelData.value.count);
    showToast({ message: `在您附近共找到 ${hotelData.value.count} 家酒店`, duration: 1500 });
  }
  // 清空之前的距离数据，防止上次的数据影响
  locationArr.value = [];

  // 获取当前位置并计算距离
  await getLocation();
  for (const { localhostLatitude, localhostLongitude } of hotelData.value
    .list) {
    let local = getDistance([localhostLatitude, localhostLongitude]);
    locationArr.value.push(local);
  }
};

let searchRegionId = useUseStore().hoteCountryCode;
//搜索接口
const getHotelInfo = async () => {
  let data = {
    limit: -1,
    page: -1,
    adult: 1,
    children: 1,
    shopName: value.value,
    regionId: searchRegionId

  };
  console.log("data:", data);
  let res = await getHotelInfoByCondition(data);
  console.log("res", res.data.data.list);
  hotelData.value = res.data.data;
  console.log(date1.value);
  console.log(dateNum.value);
};
const contaniner = ref(null);

// 滚动更新
const isRequire = ref(true);
const ScrollData = async () => {
  let res = await getShopInfoListByCondition(condition);
  console.log("滚动更新数据：", res.data.data.list);
  hotelData.value.list.push(...res.data.data.list);
  list.value = res.data.data.list;
  isRequire.value = true;
  // 清空之前的距离数据，防止上次的数据影响
  locationArr.value = [];

  // 获取当前位置并计算距离
  await getLocation();
  for (const { localhostLatitude, localhostLongitude } of hotelData.value
    .list) {
    let local = getDistance([localhostLatitude, localhostLongitude]);
    locationArr.value.push(local);
  }
  closeToast();
};

const scrollUpdata = () => {
  const scrollTop = contaniner.value.scrollTop;
  const scrollHeight = contaniner.value.scrollHeight;
  const clientHeight = contaniner.value.clientHeight;
  // console.log("scrollTop:", scrollTop);
  // console.log("scrollHeight:", scrollHeight);
  // console.log("clientHeight:", clientHeight);
  if (scrollTop + clientHeight + 5 >= scrollHeight && isRequire.value) {
    console.log("到底啦");
    condition.page += 1;
    // param.pages = 2;
    isRequire.value = false;
    if (list.value.length == 0) {
      showToast("到底啦");
      return;
    }
    ScrollData();
    console.log("condition:", condition);
    showLoadingToast({
      message: t("hotelPage.message"),
      forbidClick: true,
    });
  }
};
// 获取分区之后的数据
const getRegionId = (id) => {
  useUseStore().hoteCountryCode = id;
  console.log(useUseStore().hoteCountryCode, "酒店的id绑定到store");
  let queryParams = {
    limit: 8,
    page: 1,
    categoryId: "fwefw",
    score: "",
    regionId: useUseStore().hoteCountryCode,
    latitude: "",
    longitude: ""
  };
  isRequire.value = true;
  searchRegionId = id;
  getLocation()
    .then((location) => {
      // 提取自己的经纬度并赋值到 condition
      const { latitude, longitude } = location;
      console.log(`Latitude: ${latitude}, Longitude: ${longitude}`);
      queryParams.latitude = latitude;
      queryParams.longitude = longitude;
      // 确保经纬度设置后再调用接口
      getShopInfoListByConditionRegiond(queryParams);
    })
    .catch((error) => {
      console.error("定位失败:", error);
    });
  console.log("regiond111:", id);
};


onMounted(() => {
  initMap();

  // 获取自己的经纬度
  getLocation()
    .then((location) => {
      // 提取自己的经纬度并赋值到 condition
      const { latitude, longitude } = location;
      console.log(`Latitude: ${latitude}, Longitude: ${longitude}`);
      condition.latitude = latitude;
      condition.longitude = longitude;

      // 确保经纬度设置后再调用接口
      getShopInfoListByConditionFun(condition);

    })
    .catch((error) => {
      console.error("定位失败:", error);
    });

  console.log("contaniner.value", contaniner.value);
});

</script>

<template>
  <div id="container"></div>

  <div class="HotelPage">
    <img src="/images/Shop/backBtn1.png" alt="" class="backBtn" @click="$router.back()" />

    <div class="swiper">
      <van-swipe class="my-swiper" :show-indicators="false">
        <van-swipe-item v-for="(item, i) in 5" :key="i">
          <img src="/images/Shop/hotelSwiper.png" alt="" />
        </van-swipe-item>
      </van-swipe>
    </div>

    <div class="scheduled">
      <TabBar :title="tabBarTitle">
        <div class="content">
          <div class="item">

            <div class="right">
              <HotelRegionSelect @sendRegionId="getRegionId"></HotelRegionSelect>
              <!-- <img src="/images/Shop/hotelLogo1.png" alt="" /> -->
              <!-- <span>当前位置</span> -->
            </div>

            <div class="left">
              <form action="/">
                <van-search v-model="value" :placeholder="$t('hotelPage.name')" @search="search" :clearable="false" />
              </form>
            </div>
            <!-- 注释 -->
            <!-- <div class="right">
              <img src="/images/Shop/hotelLogo1.png" alt="" />
              <span>当前位置</span>
            </div> -->
          </div>
          <!-- 注释 -->

          <!-- <div class="item item2">
            <div class="left">
              <div class="start" @click="show = true">
                <div class="title">入住时间</div>
                <div class="info">{{ date1 }}</div>
              </div>
              <div class="num">{{ date }}</div>
              <div class="end" @click="secondShow = true">
                <div class="title">退房时间</div>
                <div class="info">{{ date2 }}</div>
              </div>
            </div>

            <div class="right">
              <div class="title">每间</div>
              <div class="info" @click="showPopup">
                {{ adultvalue }}成人 <span>{{ childvalue }}儿童</span>
              </div>
            </div>
          </div> -->
        </div>
      </TabBar>
    </div>

    <van-calendar v-model:show="show" @confirm="onConfirm" />
    <van-calendar v-model:show="secondShow" @confirm="onConfirm" />

    <!-- 底部弹出 -->
    <!-- <van-popup
      v-model:show="showBottom"
      position="bottom"
      :style="{ height: '13%' }"
    >
      <div class="sub_plus">
        <span>成人</span>
        <div class="right">
          <div class="sub" @click="decrementQuantity1">-</div>
          <div class="count">{{ adultvalue }}</div>
          <div class="plus" @click="incrementQuantity1">+</div>
        </div>
      </div>
      <div class="sub_plus">
        <span>儿童</span>
        <div class="right">
          <div class="sub" @click="decrementQuantity2">-</div>
          <div class="count">{{ childvalue }}</div>
          <div class="plus" @click="incrementQuantity2">+</div>
        </div>
      </div>
    </van-popup> -->

    <div class="hotelList">
      <div class="title">
        <span class="highlight"></span>Near
      </div>
      <van-dropdown-menu active-color="#1989fa">
        <van-dropdown-item v-model="activeSort" :options="sortOptions" @change="onSortChange" />
      </van-dropdown-menu>
      <div class="list" @scroll="scrollUpdata" ref="contaniner">
        <template v-if="hotelData">
          <div class="item" v-for="(item, i) in hotelData.list" :key="i" @click="toHotelDetailFun(item.shopId)">
            <img :src="item.userImage" alt="hotel image" />

            <div class="right">
              <div class="hotel-title">{{ item.shopName }}</div>
              <div class="tags" v-if="item.shopTagsList">
                {{ item.shopTagsList.join(", ") }}
              </div>
              <div class="address">{{ item.address }}</div>
              <div class="distance">
                距离：
                <span>{{ locationArr[i] || $t("hotelPage.nodistance") }}</span>
              </div>
              <div class="description">{{ item.shopIntroduce }}</div>
              <div class="score" v-if="item.score">
                <span>{{ item.score.toFixed(1) }}</span> <!-- 分数保留1位小数 -->
                <span class="score-comment">{{ getComment(item.score) }}</span>
                <!-- <span class="comment-count">({{ item.commentCount || 0 }}条评论)</span> -->
              </div>
              <div class="score" v-else>
                暂无评分
              </div>
            </div>
          </div>
        </template>
      </div>
    </div>

  </div>
</template>

<style lang="scss" scoped>
.HotelPage {
  background: #f5f5f5;
  max-height: 100vh;
  overflow-y: scroll;

  &::-webkit-scrollbar {
    display: none;
  }

  .sub_plus {
    margin-bottom: 20rem;
    margin-top: 20rem;
    font-size: 16rem;
    display: flex;
    justify-content: space-around;

    .right {
      display: flex;
      width: 60rem;
      justify-content: space-around;
      align-items: center;

      .sub {
        border: 1rem solid rgba(100, 46, 142, 1);
        border-radius: 50%;
        width: 13rem;
        height: 14rem;
        line-height: 13rem;
        text-align: center;
      }

      .plus {
        border: 1rem solid rgba(100, 46, 142, 1);
        border-radius: 50%;
        width: 13rem;
        height: 13rem;
        line-height: 13rem;
        text-align: center;
      }
    }
  }

  :deep(.van-calendar) {
    z-index: 99999;
    position: fixed;
    bottom: 0;
    width: 100%;
    height: 75%;
  }

  >.backBtn {
    width: 24rem;
    height: 24rem;
    position: fixed;
    left: 16rem;
    top: 16rem;
    z-index: 100;
  }

  >.swiper {
    position: fixed;
    left: 0;
    right: 0;

    >.my-swiper {
      img {
        width: 100vw;
        height: 200rem;
        object-fit: cover;
      }
    }
  }

  >.scheduled {
    position: relative;
    z-index: 200;

    padding: 18rem 16rem 0;
    background: #f5f5f5;

    margin-top: 200rem;
    border-radius: 12rem 12rem 0rem 0rem;

    >.tabBar {
      padding-bottom: 20rem;
    }

    .content {
      padding: 0 16rem;

      >.item {
        position: relative;
        padding: 16rem 0;
        border-bottom: 1rem solid #e0e0e0;
        font-size: 12rem;

        display: flex;
        justify-content: space-between;
        align-items: start;

        >.left {
          display: flex;

          // > img.logo {
          //   width: 20rem;
          //   margin-right: 8rem;
          // }

          // > span {
          //   font-size: 14rem;
          //   font-weight: 400;
          //   line-height: 20rem;
          //   color: #000;
          // }
        }

        >.right {
          display: flex;
          align-items: center;

          >img {
            width: 16rem;
            height: 16rem;
            object-fit: cover;
            margin-right: 4rem;
          }

          >span {
            font-size: 16rem;
            font-weight: 400;
            line-height: 52rem;
            color: #999;
          }
        }

        &.item2 {
          .start {
            background-color: burlywood;
          }

          .title {
            font-size: 16rem;
            font-weight: 400;
            line-height: 12rem;
            color: #999;
            margin-bottom: 8rem;
          }

          >.left {
            flex: 1;
            padding-right: 28rem;
            justify-content: space-between;
            align-items: flex-end;
            border-right: 1rem solid #e0e0e0;

            .info {
              font-size: 18rem;
              color: #000;
              text-align: center;
            }

            >.num {
              color: #999;
            }
          }

          >.right {
            padding-left: 28rem;
            flex-direction: column;
            align-items: start;

            >.info {
              color: #000;

              >span {
                color: #999;
              }
            }
          }
        }
      }
    }
  }

  >.hotelList {
    position: relative;
    z-index: 100;

    /* 标题样式 */
    >.title {
      font-size: 18px;
      /* 字体大小适中 */
      font-weight: 600;
      /* 字体加粗但不过分 */
      padding: 14px 16px;
      /* 较为紧凑的内边距 */
      color: #ffffff;
      /* 白色字体，与深紫背景形成对比 */
      background: linear-gradient(90deg, #4a006e 0%, #c30fdf 100%);
      /* 深紫到中紫的渐变，突显高端 */
      text-align: center;
      position: relative;
      border: 1px solid #4a006e;
      /* 深紫色直线边框，提升专业感 */
      box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.15);
      /* 适度阴影，增加层次感 */

      /* 两侧垂直线条装饰 */
      &:before,
      &:after {
        content: '';
        position: absolute;
        top: 0;
        bottom: 0;
        width: 3px;
        background: linear-gradient(180deg, #b952ce 0%, #31061e 100%);
        /* 垂直线渐变，与装饰条一致 */
      }

      &:before {
        left: 0;
        /* 左侧垂直线 */
      }

      &:after {
        right: 0;
        /* 右侧垂直线 */
      }
    }


    /* 酒店列表样式 */
    >.list {
      height: calc(100vh - 120px);
      /* 适配滚动区域 */
      padding: 16px;
      overflow-y: auto;
      background: #f7f8fa;

      /* 单个酒店条目 */
      >.item {
        display: flex;
        padding: 16px;
        margin-bottom: 16px;
        background: #ffffff;
        border: 1px solid #ebedf0;
        border-radius: 12px;
        transition: box-shadow 0.3s ease;
        cursor: pointer;

        &:hover {
          box-shadow: 0 8px 16px rgba(0, 0, 0, 0.15);
        }

        /* 酒店图片 */
        >img {
          width: 100px;
          height: 100px;
          border-radius: 8px;
          object-fit: cover;
          margin-right: 16px;
        }

        /* 酒店信息 */
        >.right {
          flex: 1;
          display: flex;
          flex-direction: column;
          justify-content: space-between;

          .hotel-title {
            font-size: 22px;
            font-weight: 700;
            color: #222;
            margin-bottom: 8px;
          }

          .tags {
            font-size: 13px;
            color: #999;
            margin-bottom: 8px;
            font-style: italic;
          }

          .address {
            font-size: 14px;
            color: #555;
            margin-bottom: 8px;
          }

          .distance {
            font-size: 14px;
            color: #444;
            margin-bottom: 8px;

            >span {
              font-weight: bold;
              color: #ff4d4f;
            }
          }

          .description {
            font-size: 14px;
            color: #666;
            margin-bottom: 8px;
          }

          .score {
            display: flex;
            /* 使用弹性布局 */
            align-items: center;
            padding: 6px 12px;
            background: linear-gradient(90deg, #3a7bd5 0%, #0b3c8b 100%);
            /* 蓝色渐变背景 */
            color: #ffffff;
            /* 白色字体 */
            font-size: 14px;
            /* 字体大小 */
            font-weight: bold;
            /* 加粗分数 */
            border-radius: 6px;
            /* 圆角设计 */
            min-width: 80px;
            /* 最小宽度 */
            justify-content: center;
            /* 分数居中 */
            margin-bottom: 4px;
            /* 与评语和评论数保持间距 */
          }

          .score-comment {
            font-size: 12px;
            /* 较小字体 */
            color: #dfe9e6;
            /* 灰色字体，与分数形成对比 */
            margin-left: 8px;
            /* 与分数间隔 */
          }

          .comment-count {
            font-size: 12px;
            color: #999;
            /* 次要信息使用浅灰色 */
            margin-left: 8px;
            /* 与评语间隔 */
          }

        }

        /* 移动端样式 */
        @media (max-width: 768px) {
          flex-direction: column;
          align-items: flex-start;

          >img {
            width: 100%;
            height: auto;
            margin-bottom: 10px;
          }

          >.right {
            padding: 0;
          }
        }
      }
    }
  }

}
</style>
